package com.hl.framework.db.mybatis.type;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * Set<Long> 的类型转换器实现类，对应数据库的 varchar 类型
 *
 * @author 芋道源码
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(TreeSet.class)  // 正确：明确对应TreeSet类型
public class LongSetTypeHandler implements TypeHandler<TreeSet<Long>> {

    // 核心解析逻辑：同方案1的工具类
    private TreeSet<Long> parseToTreeSet(String varcharValue) {
        if (varcharValue == null || varcharValue.trim().isEmpty()) {
            return new TreeSet<>();
        }
        String cleanStr = varcharValue.trim().replaceAll("^\\[|\\]$", "");
        if (cleanStr.isEmpty()) {
            return new TreeSet<>();
        }
        return new TreeSet<>(Arrays.stream(cleanStr.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .toList());
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, TreeSet<Long> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || parameter.isEmpty()) {
            ps.setString(i, "[]");
            return;
        }
        // 优化拼接逻辑，确保格式统一
        String value = "[" + parameter.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(",")) + "]";
        ps.setString(i, value);
    }

    @Override
    public TreeSet<Long> getResult(ResultSet rs, String columnName) throws SQLException {
        String varcharValue = rs.getString(columnName);
        return parseToTreeSet(varcharValue);
    }

    @Override
    public TreeSet<Long> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String varcharValue = rs.getString(columnIndex);
        return parseToTreeSet(varcharValue);
    }

    @Override
    public TreeSet<Long> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String varcharValue = cs.getString(columnIndex);
        return parseToTreeSet(varcharValue);
    }
}
